package com.yufuchang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by yufuchang on 2020/9/5.
 */
@RestController
public class PostController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/get_post")
    public void test() {
        // 请求地址
        String url = "http://jsonplaceholder.typicode.com/posts";

        // 要发送的数据对象
        PostBean postBean = new PostBean();
        postBean.setUserId(666);
        postBean.setTitle("faeaf");
        postBean.setBody("阿峰啊");

        // 发送post请求，并输出结果
        String result = restTemplate.postForObject(url, postBean, String.class);
        System.out.println(result);
        return;
    }

    @GetMapping("/post_form")
    public void postForm() {
        // 请求地址
        String url = "http://jsonplaceholder.typicode.com/posts";

        // 请求头设置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        //提交参数设置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("title", "faefa");
        map.add("body", "法埃尔");

        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);

        // 发送post请求，并输出结果
        String result = restTemplate.postForObject(url, request, String.class);
        System.out.println(result);
        return;
    }


    @GetMapping("/post_json")
    public void postJson() {
        // 请求地址
        String url = "http://jsonplaceholder.typicode.com/posts";

        // 要发送的数据对象
        PostBean postBean = new PostBean();
        postBean.setUserId(666);
        postBean.setTitle("fasefae");
        postBean.setBody("faoefajoiew");

        // 发送post请求，并输出结果
        ResponseEntity<String> responseEntity
                = restTemplate.postForEntity(url, postBean, String.class);
        String body = responseEntity.getBody(); // 获取响应体
        HttpStatus statusCode = responseEntity.getStatusCode(); // 获取响应码
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 获取响应码值
        HttpHeaders headers = responseEntity.getHeaders(); // 获取响应头

        System.out.println("body：" + body);
        System.out.println("statusCode：" + statusCode);
        System.out.println("statusCodeValue：" + statusCodeValue);
        System.out.println("headers：" + headers);
        return;
    }
}
